<template>
  <div class="organization-manage">
    <el-card>
      <div class="header">
        <h2>组织管理</h2>
        <el-button 
          type="primary" 
          :icon="Plus"
          v-permission="'system:organization:add'"
          @click="handleAdd"
        >
          添加组织
        </el-button>
      </div>

      <div class="content">
        <div class="tree-panel">
          <organization-tree
            ref="orgTreeRef"
            :show-checkbox="false"
            :show-member-count="true"
            @node-click="handleNodeClick"
          />
        </div>

        <div class="detail-panel">
          <el-tabs v-model="activeTab">
            <el-tab-pane label="组织信息" name="info">
              <div v-if="currentOrg" class="org-info">
                <el-descriptions :column="2" border>
                  <el-descriptions-item label="组织名称">
                    {{ currentOrg.orgName }}
                  </el-descriptions-item>
                  <el-descriptions-item label="组织编码">
                    {{ currentOrg.orgCode }}
                  </el-descriptions-item>
                  <el-descriptions-item label="组织类型">
                    {{ currentOrg.orgTypeName }}
                  </el-descriptions-item>
                  <el-descriptions-item label="负责人">
                    {{ currentOrg.leaderName || '未设置' }}
                  </el-descriptions-item>
                  <el-descriptions-item label="联系电话">
                    {{ currentOrg.phone || '-' }}
                  </el-descriptions-item>
                  <el-descriptions-item label="邮箱">
                    {{ currentOrg.email || '-' }}
                  </el-descriptions-item>
                  <el-descriptions-item label="地址" :span="2">
                    {{ currentOrg.address || '-' }}
                  </el-descriptions-item>
                  <el-descriptions-item label="状态">
                    <el-tag :type="currentOrg.status === 1 ? 'success' : 'danger'">
                      {{ currentOrg.status === 1 ? '正常' : '停用' }}
                    </el-tag>
                  </el-descriptions-item>
                  <el-descriptions-item label="成员数量">
                    {{ currentOrg.memberCount || 0 }}人
                  </el-descriptions-item>
                  <el-descriptions-item label="备注" :span="2">
                    {{ currentOrg.remark || '-' }}
                  </el-descriptions-item>
                </el-descriptions>

                <div class="actions">
                  <el-button 
                    type="primary"
                    v-permission="'system:organization:edit'"
                    @click="handleEdit(currentOrg)"
                  >
                    编辑
                  </el-button>
                  <el-button 
                    type="danger"
                    v-permission="'system:organization:delete'"
                    @click="handleDelete(currentOrg)"
                  >
                    删除
                  </el-button>
                </div>
              </div>
              <el-empty v-else description="请选择组织" />
            </el-tab-pane>

            <el-tab-pane label="组织成员" name="members">
              <div v-if="currentOrg">
                <div class="member-header">
                  <el-button 
                    type="primary" 
                    size="small"
                    v-permission="'system:organization:addMember'"
                    @click="handleAddMember"
                  >
                    添加成员
                  </el-button>
                </div>
                <el-table :data="members" style="width: 100%">
                  <el-table-column prop="nickname" label="姓名" />
                  <el-table-column prop="username" label="用户名" />
                  <el-table-column prop="titleName" label="头衔" />
                  <el-table-column prop="joinDate" label="加入日期" />
                  <el-table-column label="操作" width="200">
                    <template #default="{ row }">
                      <el-button
                        type="primary"
                        size="small"
                        text
                        v-permission="'system:organization:editMember'"
                        @click="handleEditMember(row)"
                      >
                        编辑
                      </el-button>
                      <el-button
                        type="danger"
                        size="small"
                        text
                        v-permission="'system:organization:removeMember'"
                        @click="handleRemoveMember(row)"
                      >
                        移除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <el-empty v-else description="请选择组织" />
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </el-card>

    <!-- 添加/编辑成员对话框 -->
    <el-dialog
      v-model="addMemberDialogVisible"
      :title="memberDialogTitle"
      width="600px"
      @close="handleAddMemberDialogClose"
    >
      <el-form
        ref="memberFormRef"
        :model="memberFormData"
        :rules="memberFormRules"
        label-width="100px"
      >
        <el-form-item label="选择用户" prop="userId">
          <el-select
            v-model="memberFormData.userId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入用户名搜索"
            :remote-method="searchUsers"
            :loading="userSearchLoading"
            :disabled="isEditingMember"
            style="width: 100%"
          >
            <el-option
              v-for="user in userList"
              :key="user.id"
              :label="`${user.username} (${user.nickname || '未设置昵称'})`"
              :value="user.id"
            />
          </el-select>
          <div v-if="isEditingMember" style="color: #909399; font-size: 12px; margin-top: 5px">
            编辑模式下不能修改用户
          </div>
        </el-form-item>
        <el-form-item label="选择头衔">
          <el-select
            v-model="memberFormData.titleValue"
            placeholder="请选择头衔（可选）"
            clearable
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="title in titleList"
              :key="title.dictValue"
              :label="title.dictLabel"
              :value="title.dictValue"
            >
              <div style="display: flex; justify-content: space-between; align-items: center">
                <span>{{ title.dictLabel }}</span>
                <el-tag v-if="title.remark" size="small" type="info">{{ title.remark }}</el-tag>
              </div>
            </el-option>
          </el-select>
          <div style="color: #909399; font-size: 12px; margin-top: 5px">
            头衔可在"系统管理 > 字典管理"中维护
          </div>
        </el-form-item>
        <el-form-item label="加入日期" prop="joinDate">
          <el-date-picker
            v-model="memberFormData.joinDate"
            type="date"
            placeholder="请选择加入日期"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="memberFormData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addMemberDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitMember">确定</el-button>
      </template>
    </el-dialog>

    <!-- 组织编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="上级组织" prop="parentId">
          <el-tree-select
            v-model="formData.parentId"
            :data="orgTreeData"
            :props="{ label: 'orgName', value: 'id' }"
            placeholder="请选择上级组织"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="组织名称" prop="orgName">
          <el-input v-model="formData.orgName" placeholder="请输入组织名称" />
        </el-form-item>
        <el-form-item label="组织编码" prop="orgCode">
          <el-input v-model="formData.orgCode" placeholder="请输入组织编码" />
        </el-form-item>
        <el-form-item label="组织类型" prop="orgType">
          <el-select v-model="formData.orgType" placeholder="请选择组织类型" style="width: 100%">
            <el-option
              v-for="item in orgTypeList"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="parseInt(item.dictValue)"
            >
              <span>{{ item.dictLabel }}</span>
              <span v-if="item.remark" style="float: right; color: #8492a6; font-size: 13px">
                {{ item.remark }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="formData.address" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="显示顺序" prop="orderNum">
          <el-input-number v-model="formData.orderNum" :min="0" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="formData.remark" 
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import OrganizationTree from '@/components/OrganizationTree.vue'
import {
  getOrganizationTree,
  getOrganizationById,
  createOrganization,
  updateOrganization,
  deleteOrganization,
  getOrganizationMembers,
  addOrganizationMember,
  removeOrganizationMember,
  updateUserOrganization
} from '@/api/organization'
import { getUserList } from '@/api/user'
import { getDictDataByType } from '@/api/dict'

const orgTreeRef = ref(null)
const formRef = ref(null)
const memberFormRef = ref(null)
const currentOrg = ref(null)
const activeTab = ref('info')
const members = ref([])
const dialogVisible = ref(false)
const addMemberDialogVisible = ref(false)
const dialogTitle = computed(() => formData.value.id ? '编辑组织' : '添加组织')
const memberDialogTitle = computed(() => memberFormData.value.id ? '编辑组织成员' : '添加组织成员')
const isEditingMember = ref(false)
const orgTreeData = ref([])
const orgTypeList = ref([])
const titleList = ref([])
const userList = ref([])
const userSearchLoading = ref(false)

const formData = ref({
  id: null,
  parentId: 0,
  orgName: '',
  orgCode: '',
  orgType: 2,
  leaderId: null,
  phone: '',
  email: '',
  address: '',
  orderNum: 0,
  status: 1,
  remark: ''
})

const formRules = {
  orgName: [{ required: true, message: '请输入组织名称', trigger: 'blur' }],
  orgCode: [{ required: true, message: '请输入组织编码', trigger: 'blur' }],
  orgType: [{ required: true, message: '请选择组织类型', trigger: 'change' }]
}

const memberFormData = ref({
  id: null,
  userId: null,
  orgId: null,
  titleValue: null,
  joinDate: new Date().toISOString().split('T')[0],
  remark: ''
})

const memberFormRules = {
  userId: [{ required: true, message: '请选择用户', trigger: 'change' }],
  joinDate: [{ required: true, message: '请选择加入日期', trigger: 'change' }]
}

// 加载组织树数据
const loadOrgTree = async () => {
  try {
    const res = await getOrganizationTree()
    if (res.code === 200) {
      orgTreeData.value = [{ id: 0, orgName: '顶级组织', children: res.data }]
    }
  } catch (error) {
    console.error('加载组织树失败:', error)
  }
}

// 处理节点点击
const handleNodeClick = async (data) => {
  currentOrg.value = data
  if (activeTab.value === 'members') {
    await loadMembers()
  }
}

// 加载成员列表
const loadMembers = async () => {
  if (!currentOrg.value) return
  
  try {
    const res = await getOrganizationMembers(currentOrg.value.id)
    if (res.code === 200) {
      members.value = res.data || []
      console.log('加载成员列表成功:', members.value)
    } else {
      console.error('加载成员列表失败，错误码:', res.code, '错误信息:', res.message)
      ElMessage.error(res.message || '加载成员列表失败')
      members.value = []
    }
  } catch (error) {
    console.error('加载成员列表异常:', error)
    if (error.response && error.response.data) {
      ElMessage.error(error.response.data.message || '加载成员列表失败')
    } else {
      ElMessage.error('加载成员列表失败，请检查网络或权限')
    }
    members.value = []
  }
}

// 添加组织
const handleAdd = () => {
  formData.value = {
    id: null,
    parentId: currentOrg.value?.id || 0,
    orgName: '',
    orgCode: '',
    orgType: 2,
    leaderId: null,
    phone: '',
    email: '',
    address: '',
    orderNum: 0,
    status: 1,
    remark: ''
  }
  dialogVisible.value = true
}

// 编辑组织
const handleEdit = (org) => {
  formData.value = { ...org }
  dialogVisible.value = true
}

// 删除组织
const handleDelete = async (org) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除组织【${org.orgName}】吗？`,
      '删除确认',
      { type: 'warning' }
    )
    
    await deleteOrganization(org.id)
    ElMessage.success('删除成功')
    orgTreeRef.value?.refresh()
    currentOrg.value = null
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除组织失败:', error)
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  await formRef.value.validate()
  
  try {
    if (formData.value.id) {
      await updateOrganization(formData.value)
      ElMessage.success('更新成功')
    } else {
      await createOrganization(formData.value)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    orgTreeRef.value?.refresh()
    loadOrgTree()
  } catch (error) {
    console.error('保存组织失败:', error)
  }
}

// 关闭对话框
const handleDialogClose = () => {
  formRef.value?.resetFields()
}

// 加载组织类型字典
const loadOrgTypes = async () => {
  try {
    const res = await getDictDataByType('sys_org_type')
    if (res.code === 200) {
      orgTypeList.value = res.data
    }
  } catch (error) {
    console.error('加载组织类型失败:', error)
  }
}

// 加载头衔字典
const loadTitles = async () => {
  try {
    const res = await getDictDataByType('sys_title')
    if (res.code === 200) {
      titleList.value = res.data
    }
  } catch (error) {
    console.error('加载头衔列表失败:', error)
    ElMessage.error('加载头衔列表失败')
  }
}

// 搜索用户
const searchUsers = async (query) => {
  if (!query) {
    userList.value = []
    return
  }
  
  userSearchLoading.value = true
  try {
    const res = await getUserList({ username: query, current: 1, size: 20 })
    if (res.code === 200) {
      userList.value = res.data.records || []
    }
  } catch (error) {
    console.error('搜索用户失败:', error)
  } finally {
    userSearchLoading.value = false
  }
}

// 添加成员
const handleAddMember = async () => {
  if (!currentOrg.value) {
    ElMessage.warning('请先选择组织')
    return
  }
  
  isEditingMember.value = false
  memberFormData.value = {
    id: null,
    userId: null,
    orgId: currentOrg.value.id,
    titleValue: null,
    joinDate: new Date().toISOString().split('T')[0],
    remark: ''
  }
  
  // 先加载头衔列表，然后再打开对话框
  await loadTitles()
  addMemberDialogVisible.value = true
}

// 编辑成员
const handleEditMember = async (member) => {
  if (!currentOrg.value) {
    ElMessage.warning('请先选择组织')
    return
  }
  
  isEditingMember.value = true
  
  // 先加载头衔列表
  await loadTitles()
  
  // 填充表单数据
  memberFormData.value = {
    id: member.id || null,
    userId: member.userId,
    orgId: currentOrg.value.id,
    titleValue: member.titleValue || null,
    joinDate: member.joinDate,
    remark: member.remark || ''
  }
  
  // 如果有用户信息，添加到用户列表中以便显示
  if (member.username) {
    userList.value = [{
      id: member.userId,
      username: member.username,
      nickname: member.nickname || '未设置昵称'
    }]
  }
  
  addMemberDialogVisible.value = true
}

// 提交添加/编辑成员
const handleSubmitMember = async () => {
  await memberFormRef.value.validate()
  
  try {
    // 准备提交数据，titleValue作为字典值
    const submitData = {
      userId: memberFormData.value.userId,
      orgId: memberFormData.value.orgId,
      titleValue: memberFormData.value.titleValue || null,
      joinDate: memberFormData.value.joinDate,
      remark: memberFormData.value.remark
    }
    
    if (isEditingMember.value) {
      // 编辑成员
      await updateUserOrganization(submitData)
      ElMessage.success('编辑成员成功')
    } else {
      // 添加成员
      await addOrganizationMember(submitData)
      ElMessage.success('添加成员成功')
    }
    
    addMemberDialogVisible.value = false
    await loadMembers()
    // 刷新组织树以更新成员数量
    orgTreeRef.value?.refresh()
  } catch (error) {
    console.error(isEditingMember.value ? '编辑成员失败:' : '添加成员失败:', error)
  }
}

// 关闭添加成员对话框
const handleAddMemberDialogClose = () => {
  memberFormRef.value?.resetFields()
  userList.value = []
}

// 移除成员
const handleRemoveMember = async (member) => {
  try {
    await ElMessageBox.confirm(
      `确定要将【${member.nickname}】从当前组织移除吗？`,
      '移除确认',
      { type: 'warning' }
    )
    
    await removeOrganizationMember(member.userId, currentOrg.value.id)
    ElMessage.success('移除成功')
    await loadMembers()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('移除成员失败:', error)
    }
  }
}

// 监听标签页切换
watch(activeTab, async (newTab) => {
  if (newTab === 'members' && currentOrg.value) {
    await loadMembers()
  }
})

onMounted(() => {
  loadOrgTree()
  loadOrgTypes()
  loadTitles()
})
</script>

<style scoped>
.organization-manage {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.content {
  display: flex;
  gap: 20px;
  height: 600px;
}

.tree-panel {
  flex: 1;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 10px;
  overflow-y: auto;
}

.detail-panel {
  flex: 2;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 10px;
  overflow-y: auto;
}

.org-info {
  padding: 10px;
}

.actions {
  margin-top: 20px;
  display: flex;
  gap: 10px;
}

.member-header {
  margin-bottom: 15px;
}
</style>

